package com.d2.modules.system.permission.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.d2.common.domain.Result;
import com.d2.modules.system.permission.entity.Role;
import com.d2.modules.system.permission.entity.RoleResource;
import com.d2.modules.system.permission.service.IResourceService;
import com.d2.modules.system.permission.service.IRoleResourceService;
import com.d2.modules.system.permission.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleResourceService roleResourceService;

    @Autowired
    private IResourceService resourceService;


    @GetMapping("list")
    public Result<List<Role>> list() {
        return Result.success(roleService.list());
    }

    @GetMapping("page")
    public Result<Page<Role>> page(Page<Role> page) {
        page = this.roleService.page(page);
        return Result.success(page);
    }

    @PostMapping("update")
    public Result<Void> update(@RequestBody Role obj) {
//        obj.setUpdateTime(null);
        this.roleService.updateById(obj);
        return Result.success();
    }

    @PostMapping("add")
    public Result<Void> add(@RequestBody Role obj) {
//        obj.setUpdateTime(null);
        this.roleService.save(obj);
        return Result.success();
    }


    @GetMapping("getPermission")
    public Result<?> getPermission(Long roleId) {
//        obj.setUpdateTime(null);
        RoleResource roleResource = new RoleResource();
        roleResource.setRoleId(roleId);
        List<RoleResource> list = roleResourceService.list(new QueryWrapper<>(roleResource));
        List<Long> collect = list.stream().map(RoleResource::getResourceId).collect(Collectors.toList());
        return Result.success(collect);
    }

    @Transactional
    @PostMapping("authz")
    public Result<?> authz(Long roleId, @RequestBody List<Long> list) {
        RoleResource query = new RoleResource();
        query.setRoleId(roleId);

        List<RoleResource> roleResourceList = new ArrayList<>();
        roleResourceService.remove(new QueryWrapper<>(query));
        list.forEach(resourceId -> {
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(roleId);
            roleResource.setResourceId(resourceId);
            roleResourceList.add(roleResource);
        });
        roleResourceService.saveBatch(roleResourceList);
        return Result.success();
    }
}
